import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    TextInput,
    AsyncStorage
} from 'react-native';
import {
    Actions
} from 'react-native-router-flux';
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const {height, width} = Dimensions.get('window');
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
export default class LoginPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/user/getInfo',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    if(this.state.token!==''){
                        Actions.EnquiriesTabPage({area:responseJson.data.area})
                    }else {
                        null
                    }
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            phone:'',
            password:'',
            token:'',
        }
    };

    login=()=>{
        let re = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,23}$/;
        let checkPassword = re.test(this.state.password);
        if(this.state.password===''){
            alert('密码不能为空')
        }else if(this.state.phone.length!==11){
            alert('手机账号长度错误')
        }else if(checkPassword!==true){
            alert(checkPassword)
        }else if(this.state.phone[0]!=1){
            alert('手机号不正确')
        }else {
            let login={
                "phone":this.state.phone,
                "password":this.state.password,
                "type":"password"
            };
            ModalIndicator.show("正在请求数据......");
            fetch(Config.baseApi+'/user/login',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: Utils.getParamsString(login)
            })
                .then((response) => response.json())
                .then((responseJson) => {
                    ModalIndicator.hide();
                    if(responseJson.status===0){
                        AsyncStorage.removeItem(STORAGE_KEY_TOKEN);
                        AsyncStorage.setItem(STORAGE_KEY_TOKEN,responseJson.data.token);
                        Actions.EnquiriesTabPage({area:responseJson.data.area})
                    }else{
                        Toast.message(responseJson.msg);
                    }
                })
                .catch((error) => {
                    ModalIndicator.hide();
                    Toast.message(error);
                });
        }
    };




    render() {
        return (
            <View style={styles.container}>
                <View style={styles.topTitle}>
                    <Text style={styles.topTitleMsg}>手机号登录</Text>
                </View>
                <View style={styles.phoneAndPasswordView}>
                    <View style={styles.topTextInputView}>
                        <Text style={styles.TextInputTitleMsg}>手机号</Text>
                        <TextInput
                            ref={ (ref)=>this.topTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.phone}
                            keyboardType={"numeric"}
                            placeholder="请输入手机号"
                            placeholderTextColor='#bababa'
                            autoCorrect={false}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    phone:text,
                                })
                            }}/>
                    </View>
                    <View style={styles.bottomTextInputView}>
                        <Text style={styles.TextInputTitleMsg}>密码</Text>
                        <TextInput
                            ref={ (ref)=>this.topTextInput = ref }
                            autoCapitalize={"none"}
                            defaultValue={this.state.password}
                            placeholder="请输入密码"
                            placeholderTextColor='#bababa'
                            autoCorrect={false}
                            secureTextEntry={true}
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    password:text,
                                })
                            }}/>
                    </View>
                </View>
                <View style={styles.ButView}>
                    <TouchableOpacity onPress={()=>this.goPage()}>
                        <Text style={styles.ButMsg}>用短信验证码登录</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={()=>this.registration()}>
                        <Text style={styles.ButMsg}>注册</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.loginView}>
                    {this.state.phone.length>0||this.state.password>0
                    ?(<TouchableOpacity
                            onPress={()=>this.login()}
                            style={styles.loginButChangeView}>
                            <Text style={styles.loginButMsg}>登录</Text>
                        </TouchableOpacity>)
                    :(<TouchableOpacity
                            onPress={()=>this.login()}
                            style={styles.loginButView}>
                            <Text style={styles.loginButMsg}>登录</Text>
                        </TouchableOpacity>)}
                </View>
            </View>
        );
    }
    goPage=()=>{
        Actions.VerificationLoginPage()
    };
    registration=()=>{
        Actions.RegistrationPage()
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#ffffff'
    },
    topTitle:{
        marginTop:109,
        marginLeft:30
    },
    topTitleMsg:{
        fontSize:20,
        color:'#000000'
    },
    phoneAndPasswordView:{
        marginTop:24,
        marginLeft:30
    },
    topTextInputView:{
        width:width-60,
        flexDirection:'row',
        alignItems:'center',
        height:40,
        borderColor:'#bababa',
        borderBottomWidth:1
    },
    TextInputTitleMsg:{
        fontSize:15,
        color:'#000000'
    },
    bottomTextInputView:{
        width:width-60,
        flexDirection:'row',
        alignItems:'center',
        height:40,
        borderColor:'#bababa',
        borderBottomWidth:1
    },
    ButView:{
        marginTop:28,
        width:width-60,
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center',
        marginLeft:30
    },
    ButMsg:{
        fontSize:13,
        color:'#3090dd'
    },
    loginView:{
        marginTop:39,
        justifyContent:'center',
        alignItems:'center'
    },
    loginButView:{
        width:width-60,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#69a9dd',
        borderRadius:5,
        height:44
    },
    loginButMsg:{
        color:'#ffffff',
        textAlign:'center',
        fontSize:17
    },
    textInputView:{
        position: 'absolute',
        left:105,
        height:40,
        width:width-165,
        fontSize:15
    },
    loginButChangeView:{
        width:width-60,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#3090dd',
        borderRadius:5,
        height:44
    }
});
